﻿Imports System
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.ComponentModel.Design.Serialization
Imports System.Configuration
Imports System.Globalization
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Workflow.ComponentModel
Imports System.Workflow.ComponentModel.Design
Imports System.Workflow.ComponentModel.Serialization
Imports System.Xml

Namespace System.Workflow.ComponentModel.Compiler
    Friend Class XomlCompilerHelper
        ' Methods
        Private Shared Function CheckFileNameUsingPaths(ByVal fileName As String, ByVal paths As StringCollection, <Out> ByRef fullFileName As String) As Boolean
            fullFileName = Nothing
            Dim str As String = fileName.Trim(New Char() { """"c })
            Dim info As New FileInfo(str)
            If (str.Length <> info.Name.Length) Then
                If info.Exists Then
                    fullFileName = info.FullName
                End If
                Return info.Exists
            End If
            [Using] enumerator As StringEnumerator = paths.GetEnumerator
                Do While enumerator.MoveNext
                    Dim str3 As String = (enumerator.Current & Path.DirectorySeparatorChar & str)
                    Dim info2 As New FileInfo(str3)
                    If info2.Exists Then
                        fullFileName = str3
                        Return True
                    End If
                Loop
            End [Using]
            Return False
        End Function

        Friend Shared Function CheckPathName(ByVal pathName As String) As Boolean
            Return Directory.Exists(pathName.Trim(New Char() { """"c }).TrimEnd(New Char() { Path.DirectorySeparatorChar }))
        End Function

        Friend Shared Function CloneCompilerParameters(ByVal sourceParams As WorkflowCompilerParameters) As CompilerParameters
            Dim parameters As New CompilerParameters { _
                .CompilerOptions = sourceParams.CompilerOptions _
            }
            If (Not parameters.CompilerOptions Is Nothing) Then
                parameters.CompilerOptions = parameters.CompilerOptions.Replace(" /nocode", "")
                parameters.CompilerOptions = parameters.CompilerOptions.Replace("/nocode", "")
                parameters.CompilerOptions = parameters.CompilerOptions.Replace(" /checktypes", "")
                parameters.CompilerOptions = parameters.CompilerOptions.Replace("/checktypes", "")
            End If
            Dim str As String
            For Each str In sourceParams.EmbeddedResources
                parameters.EmbeddedResources.Add(str)
            Next
            parameters.Evidence = sourceParams.Evidence
            parameters.GenerateExecutable = sourceParams.GenerateExecutable
            parameters.GenerateInMemory = sourceParams.GenerateInMemory
            parameters.IncludeDebugInformation = sourceParams.IncludeDebugInformation
            Dim str2 As String
            For Each str2 In sourceParams.LinkedResources
                parameters.LinkedResources.Add(str2)
            Next
            parameters.MainClass = sourceParams.MainClass
            parameters.OutputAssembly = sourceParams.OutputAssembly
            Dim str3 As String
            For Each str3 In sourceParams.ReferencedAssemblies
                parameters.ReferencedAssemblies.Add(str3)
            Next
            parameters.TreatWarningsAsErrors = sourceParams.TreatWarningsAsErrors
            parameters.UserToken = sourceParams.UserToken
            parameters.WarningLevel = sourceParams.WarningLevel
            parameters.Win32Resource = sourceParams.Win32Resource
            Return parameters
        End Function

        Friend Shared Function CreateXomlCompilerError(ByVal [error] As ValidationError, ByVal parameters As WorkflowCompilerParameters) As WorkflowCompilerError
            Dim error2 As New WorkflowCompilerError(XomlCompilerHelper.GetFileName([error]), CInt(XomlCompilerHelper.GetValue([error], XomlCompilerHelper.LineNumber)), CInt(XomlCompilerHelper.GetValue([error], XomlCompilerHelper.ColumnNumber)), String.Empty, XomlCompilerHelper.GetPrettifiedErrorText([error]))
            If Not parameters.TreatWarningsAsErrors Then
                error2.IsWarning = [error].IsWarning
            End If
            error2.ErrorNumber = ("WF" & [error].ErrorNumber.ToString(CultureInfo.InvariantCulture))
            If (Not [error].UserData Is Nothing) Then
                Dim entry As DictionaryEntry
                For Each entry In [error].UserData
                    If ((entry.Key Is GetType(Activity)) AndAlso TypeOf entry.Value Is Activity) Then
                        error2.UserData.Item(entry.Key) = DirectCast(entry.Value, Activity).QualifiedName
                    Else
                        error2.UserData.Item(entry.Key) = entry.Value
                    End If
                Next
            End If
            Return error2
        End Function

        Friend Shared Sub FixReferencedAssemblies(ByVal parameters As CompilerParameters, ByVal results As WorkflowCompilerResults, ByVal libraryPaths As StringCollection)
            Dim str As String
            For Each str In XomlCompilerHelper.StandardAssemblies
                Dim flag As Boolean = True
                Dim str2 As String
                For Each str2 In parameters.ReferencedAssemblies
                    If ((Not str2 Is Nothing) AndAlso (str2.Length > 0)) Then
                        Dim fileName As String = Path.GetFileName(str2)
                        Dim strB As String = Path.GetFileName(str)
                        If (((Not fileName Is Nothing) AndAlso (Not strB Is Nothing)) AndAlso (String.Compare(fileName, strB, StringComparison.OrdinalIgnoreCase) = 0)) Then
                            flag = False
                            Exit For
                        End If
                    End If
                Next
                If flag Then
                    parameters.ReferencedAssemblies.Add(str)
                End If
            Next
            Dim strings As StringCollection = XomlCompilerHelper.ResolveAssemblyReferences(parameters.ReferencedAssemblies, XomlCompilerHelper.GetCompleteLibraryPaths(libraryPaths), results)
            parameters.ReferencedAssemblies.Clear
            Dim str5 As String
            For Each str5 In strings
                If Not parameters.ReferencedAssemblies.Contains(str5) Then
                    parameters.ReferencedAssemblies.Add(str5)
                End If
            Next
        End Sub

        Friend Shared Function GenerateFiles(ByVal codeDomProvider As CodeDomProvider, ByVal parameters As CompilerParameters, ByVal ccus As CodeCompileUnit()) As String()
            Dim options As New CodeGeneratorOptions { _
                .BracingStyle = "C" _
            }
            Dim strArray As String() = New String(ccus.Length  - 1) {}
            Dim i As Integer
            For i = 0 To ccus.Length - 1
                XomlCompilerHelper.ResolveReferencedAssemblies(parameters, ccus(i))
                strArray(i) = parameters.TempFiles.AddExtension((i & codeDomProvider.FileExtension))
                Dim stream As Stream = New FileStream(strArray(i), FileMode.Create, FileAccess.Write, FileShare.Read)
                Try 
                    [Using] writer As StreamWriter = New StreamWriter(stream, Encoding.UTF8)
                        codeDomProvider.GenerateCodeFromCompileUnit(ccus(i), writer, options)
                        writer.Flush
                    End [Using]
                Finally
                    stream.Close
                End Try
            Next i
            Return strArray
        End Function

        Private Shared Function GetCompleteLibraryPaths(ByVal userLibraryPaths As StringCollection) As StringCollection
            Dim strings As New StringCollection
            strings.Add(Environment.CurrentDirectory)
            Dim runtimeDirectory As String = RuntimeEnvironment.GetRuntimeDirectory
            strings.Add(runtimeDirectory.TrimEnd(New Char() { Path.DirectorySeparatorChar }))
            Dim productInstallDirectory As String = Helpers.ProductInstallDirectory
            If ((Not productInstallDirectory Is Nothing) AndAlso (productInstallDirectory.Length > 0)) Then
                strings.Add(productInstallDirectory.TrimEnd(New Char() { Path.DirectorySeparatorChar }))
            End If
            Dim array As String() = New String(userLibraryPaths.Count  - 1) {}
            userLibraryPaths.CopyTo(array, 0)
            strings.AddRange(array)
            Dim environmentVariable As String = Environment.GetEnvironmentVariable("LIB")
            If ((Not environmentVariable Is Nothing) AndAlso (environmentVariable.Length > 0)) Then
                Dim strArray2 As String() = Environment.GetEnvironmentVariable("LIB").Split(New Char() { ","c, ";"c })
                strings.AddRange(strArray2)
            End If
            Return strings
        End Function

        Private Shared Function GetFileName(ByVal [error] As ValidationError) As String
            Dim parent As Activity = [TryCast]([error].UserData.Item(GetType(Activity)),Activity)
            Do While ((Not parent Is Nothing) AndAlso (Not parent.Parent Is Nothing))
                parent = parent.Parent
            Loop
            Dim str As String = String.Empty
            If (Not parent Is Nothing) Then
                str = [TryCast](parent.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty),String)
            End If
            If (str Is Nothing) Then
                str = String.Empty
            End If
            Return str
        End Function

        Private Shared Function GetPrettifiedErrorText(ByVal [error] As ValidationError) As String
            Dim errorText As String = [error].ErrorText
            Dim activity As Activity = [TryCast]([error].UserData.Item(GetType(Activity)),Activity)
            If (activity Is Nothing) Then
                Return errorText
            End If
            Dim str2 As String = If((Not Helpers.GetRootActivity(activity) Is activity), activity.QualifiedName, activity.GetType.Name)
            If ((str2 Is Nothing) OrElse (str2.Length = 0)) Then
                str2 = SR.GetString("EmptyValue")
            End If
            If [error].IsWarning Then
                Return (SR.GetString("Warning_ActivityValidation", New Object() { str2 }) & " " & errorText)
            End If
            Return (SR.GetString("Error_ActivityValidation", New Object() { str2 }) & " " & errorText)
        End Function

        Private Shared Function GetValue(ByVal [error] As ValidationError, ByVal key As Object) As UInt32
            Dim parent As Activity = [TryCast]([error].UserData.Item(GetType(Activity)),Activity)
            Do While ((Not parent Is Nothing) AndAlso (Not parent.Parent Is Nothing))
                parent = parent.Parent
            Loop
            Dim num As UInt32 = 0
            If ((Not parent Is Nothing) AndAlso (Not parent.UserData.Item(key) Is Nothing)) Then
                num = DirectCast(parent.UserData.Item(key), UInt32)
            End If
            Return num
        End Function

        Friend Shared Function HasCodeWithin(ByVal rootActivity As Activity) As Boolean
            Dim hasCodeWithin As Boolean = False
            Dim walker As New Walker
            AddHandler walker.FoundActivity, Function (ByVal walker As Walker, ByVal e As WalkerEventArgs) 
                Dim currentActivity As Activity = e.CurrentActivity
                If Not currentActivity.Enabled Then
                    e.Action = WalkerAction.Skip
                Else
                    Dim members As CodeTypeMemberCollection = [TryCast](currentActivity.GetValue(WorkflowMarkupSerializer.XCodeProperty),CodeTypeMemberCollection)
                    If ((Not members Is Nothing) AndAlso (members.Count <> 0)) Then
                        hasCodeWithin = True
                        e.Action = WalkerAction.Abort
                    End If
                End If
            End Function
            walker.Walk(rootActivity)
            Return hasCodeWithin
        End Function

        Friend Shared Sub InternalCompileFromDomBatch(ByVal files As String(), ByVal codeFiles As String(), ByVal parameters As WorkflowCompilerParameters, ByVal results As WorkflowCompilerResults, ByVal localAssemblyPath As String)
            Dim str As String
            For Each str In parameters.LibraryPaths
                If Not XomlCompilerHelper.CheckPathName(str) Then
                    Dim num5 As Integer = &H160
                    Dim error As New WorkflowCompilerError(String.Empty, 0, 0, num5.ToString(CultureInfo.InvariantCulture), String.Format(CultureInfo.CurrentCulture, SR.GetString("LibraryPathIsInvalid"), New Object() { str })) { _
                        .IsWarning = True _
                    }
                    results.Errors.Add([error])
                End If
            Next
            Dim section As List([Of] AuthorizedType) = Nothing
            If parameters.CheckTypes Then
                Try 
                    section = [TryCast](ConfigurationManager.GetSection("System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes"),List([Of] AuthorizedType))
                Catch obj1 As Object
                End Try
                If (section Is Nothing) Then
                    Dim error2 As New ValidationError(SR.GetString("Error_ConfigFileMissingOrInvalid"), &H178)
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error2, parameters))
                    Return
                End If
            End If
            Dim provider As ITypeProvider = [TryCast](parameters.ServiceProvider.GetService(GetType(ITypeProvider)),ITypeProvider)
            Dim list2 As New ArrayList
            [Using] reader As PDBReader = New PDBReader(localAssemblyPath)
                Dim type As Type
                For Each type In provider.LocalAssembly.GetTypes
                    If (TypeProvider.IsAssignable(GetType(Activity), type) AndAlso Not type.IsAbstract) Then
                        Dim fileLocation As String = String.Empty
                        Dim customAttributes As WorkflowMarkupSourceAttribute() = DirectCast(type.GetCustomAttributes(GetType(WorkflowMarkupSourceAttribute), False), WorkflowMarkupSourceAttribute())
                        If ((Not customAttributes Is Nothing) AndAlso (customAttributes.Length > 0)) Then
                            fileLocation = customAttributes(0).FileName
                        Else
                            Dim constructor As ConstructorInfo = type.GetConstructor(Type.EmptyTypes)
                            If (Not constructor Is Nothing) Then
                                Try 
                                    Dim line As UInt32 = 0
                                    Dim column As UInt32 = 0
                                    reader.GetSourceLocationForOffset(DirectCast(constructor.MetadataToken, UInt32), 0, fileLocation, line, column)
                                Catch obj2 As Object
                                End Try
                            End If
                            If String.IsNullOrEmpty(fileLocation) Then
                                Dim info2 As MethodInfo = type.GetMethod("InitializeComponent", (BindingFlags.NonPublic Or (BindingFlags.Public Or BindingFlags.Instance)), Nothing, Type.EmptyTypes, Nothing)
                                If (Not info2 Is Nothing) Then
                                    Try 
                                        Dim num3 As UInt32 = 0
                                        Dim num4 As UInt32 = 0
                                        reader.GetSourceLocationForOffset(DirectCast(info2.MetadataToken, UInt32), 0, fileLocation, num3, num4)
                                        If Not String.IsNullOrEmpty(fileLocation) Then
                                            If fileLocation.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase) Then
                                                fileLocation = (fileLocation.Substring(0, (fileLocation.Length - ".designer.cs".Length)) & ".cs")
                                            ElseIf fileLocation.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase) Then
                                                fileLocation = (fileLocation.Substring(0, (fileLocation.Length - ".designer.vb".Length)) & ".vb")
                                            End If
                                        End If
                                    Catch obj3 As Object
                                    End Try
                                End If
                            End If
                        End If
                        Dim activity As Activity = Nothing
                        Try 
                            Try 
                                Activity.ActivityType = type
                                activity = [TryCast](Activator.CreateInstance(type),Activity)
                            Finally
                                Activity.ActivityType = Nothing
                            End Try
                            activity.UserData.Item(UserDataKeys.CustomActivity) = False
                            If TypeOf activity Is CompositeActivity Then
                                Dim activity2 As CompositeActivity = [TryCast](activity,CompositeActivity)
                                If activity2.CanModifyActivities Then
                                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(New ValidationError(SR.GetString("Error_Missing_CanModifyProperties_False", New Object() { activity.GetType.FullName }), &H117), parameters))
                                End If
                            End If
                            If (customAttributes.Length > 0) Then
                                Dim manager As New DesignerSerializationManager(parameters.ServiceProvider)
                                Dim activity3 As Activity = Nothing
                                [Using] manager.CreateSession
                                    Dim serializationManager As New WorkflowMarkupSerializationManager(manager) { _
                                        .LocalAssembly = parameters.LocalAssembly _
                                    }
                                    [Using] reader2 As XmlReader = XmlReader.Create(customAttributes(0).FileName)
                                        activity3 = [TryCast](New WorkflowMarkupSerializer().Deserialize(serializationManager, reader2),Activity)
                                    End [Using]
                                End [Using]
                                If TypeOf activity3 Is CompositeActivity Then
                                    ActivityMarkupSerializer.ReplaceChildActivities([TryCast](activity,CompositeActivity), [TryCast](activity3,CompositeActivity))
                                End If
                            End If
                        Catch exception As TargetInvocationException
                            If (TypeOf exception.InnerException Is TypeInitializationException AndAlso (Not exception.InnerException.InnerException Is Nothing)) Then
                                results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(New ValidationError(SR.GetString("Error_CustomActivityCantCreate", New Object() { type.FullName, exception.InnerException.InnerException.ToString }), &H117), parameters))
                            ElseIf (Not exception.InnerException.InnerException Is Nothing) Then
                                results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(New ValidationError(exception.InnerException.InnerException.ToString, &H117), parameters))
                            Else
                                results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(New ValidationError(SR.GetString("Error_CustomActivityCantCreate", New Object() { type.FullName, exception.InnerException.ToString }), &H117), parameters))
                            End If
                            goto Label_0526
                        Catch exception2 As Exception
                            results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(New ValidationError(SR.GetString("Error_CustomActivityCantCreate", New Object() { type.FullName, exception2.ToString }), &H117), parameters))
                            goto Label_0526
                        End Try
                        activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileLocation)
                        activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName)
                        XomlCompilerHelper.ValidateActivity(activity, parameters, results)
                        list2.Add(activity)
                    Label_0526:
                    End If
                Next
            End [Using]
            Dim pair As KeyValuePair([Of] Object, Exception)
            For Each pair In provider.TypeLoadErrors
                Dim num7 As Integer = &H161
                Dim error3 As New WorkflowCompilerError(String.Empty, 0, 0, num7.ToString(CultureInfo.InvariantCulture), pair.Value.Message) { _
                    .IsWarning = True _
                }
                results.Errors.Add(error3)
            Next
            results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results)
            Dim service As IWorkflowCompilerOptionsService = [TryCast](parameters.ServiceProvider.GetService(GetType(IWorkflowCompilerOptionsService)),IWorkflowCompilerOptionsService)
            If (service Is Nothing) Then
                Throw New Exception(SR.GetString("General_MissingService", New Object() { GetType(IWorkflowCompilerOptionsService).FullName }))
            End If
            WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, service.RootNamespace, CompilerHelpers.GetSupportedLanguage(parameters.ServiceProvider))
            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, service.RootNamespace, CompilerHelpers.GetSupportedLanguage(parameters.ServiceProvider))
            If Not results.Errors.HasErrors Then
                Dim manager3 As New CodeGenerationManager(parameters.ServiceProvider)
                manager3.Context.Push(results.CompiledUnit.Namespaces)
                Dim activity4 As Activity
                For Each activity4 In list2
                    If (activity4.Parent Is Nothing) Then
                        Dim generator As ActivityCodeGenerator
                        For Each generator In manager3.GetCodeGenerators(activity4.GetType)
                            generator.GenerateCode(manager3, activity4)
                        Next
                    End If
                Next
                If (Not parameters.GenerateCodeCompileUnitOnly OrElse parameters.CheckTypes) Then
                    Dim codeDomProvider As CodeDomProvider = CompilerHelpers.GetCodeDomProvider(CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse))
                    Dim list3 As New ArrayList(DirectCast(parameters.UserCodeCompileUnits, ICollection))
                    list3.Add(results.CompiledUnit)
                    Dim list4 As New ArrayList
                    list4.AddRange(codeFiles)
                    list4.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, parameters, DirectCast(list3.ToArray(GetType(CodeCompileUnit)), CodeCompileUnit())))
                    Dim results2 As CompilerResults = codeDomProvider.CompileAssemblyFromFile(parameters, DirectCast(list4.ToArray(GetType(String)), String()))
                    results.AddCompilerErrorsFromCompilerResults(results2)
                    results.PathToAssembly = results2.PathToAssembly
                    results.Evidence = results2.Evidence
                    results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue
                    If (Not results.Errors.HasErrors AndAlso parameters.CheckTypes) Then
                        Dim str3 As String
                        For Each str3 In MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location)
                            Dim flag As Boolean = False
                            Dim type2 As AuthorizedType
                            For Each type2 In section
                                If type2.RegularExpression.IsMatch(str3) Then
                                    flag = (String.Compare(Boolean.TrueString, type2.Authorized, StringComparison.OrdinalIgnoreCase) = 0)
                                    If Not flag Then
                                        Exit For
                                    End If
                                End If
                            Next
                            If Not flag Then
                                Dim error4 As New ValidationError(SR.GetString("Error_TypeNotAuthorized", New Object() { str3 }), &H16B)
                                results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error4, parameters))
                            End If
                        Next
                    End If
                    If (((Not results.Errors.HasErrors AndAlso Not parameters.GenerateCodeCompileUnitOnly) AndAlso parameters.GenerateInMemory) AndAlso (String.IsNullOrEmpty(parameters.CompilerOptions) OrElse Not parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign"))) Then
                        results.CompiledAssembly = results2.CompiledAssembly
                    End If
                End If
            End If
        End Sub

        Friend Shared Function MorphIntoFriendlyValidationErrors(ByVal errors As IEnumerable([Of] ValidationError)) As ValidationErrorCollection
            Dim errors2 As New ValidationErrorCollection
            Dim error As ValidationError
            For Each error In errors
                If (Not [error] Is Nothing) Then
                    If ([error].GetType Is GetType(ValidationError)) Then
                        Dim item As New ValidationError(XomlCompilerHelper.GetPrettifiedErrorText([error]), [error].ErrorNumber, [error].IsWarning)
                        errors2.Add(item)
                    Else
                        errors2.Add([error])
                    End If
                End If
            Next
            Return errors2
        End Function

        Private Shared Function ResolveAssemblyReferences(ByVal originalReferences As StringCollection, ByVal libraryPaths As StringCollection, ByVal results As WorkflowCompilerResults) As StringCollection
            Dim strings As New StringCollection
            Dim str As String
            For Each str In originalReferences
                Dim str2 As String
                If XomlCompilerHelper.CheckFileNameUsingPaths(str, libraryPaths, str2) Then
                    strings.Add(str2)
                Else
                    Dim num As Integer = &H162
                    Dim error As New WorkflowCompilerError(String.Empty, 0, 0, num.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_ReferencedAssemblyIsInvalid", New Object() { str }))
                    results.Errors.Add([error])
                End If
            Next
            Return strings
        End Function

        Private Shared Sub ResolveReferencedAssemblies(ByVal parameters As CompilerParameters, ByVal cu As CodeCompileUnit)
            If (cu.ReferencedAssemblies.Count > 0) Then
                Dim str As String
                For Each str In cu.ReferencedAssemblies
                    If Not parameters.ReferencedAssemblies.Contains(str) Then
                        parameters.ReferencedAssemblies.Add(str)
                    End If
                Next
            End If
        End Sub

        Friend Shared Sub ValidateActivity(ByVal activity As Activity, ByVal parameters As WorkflowCompilerParameters, ByVal results As WorkflowCompilerResults)
            Dim manager As New ValidationManager(parameters.ServiceProvider)
            Dim validator As Validator
            For Each validator In manager.GetValidators(activity.GetType)
                Try 
                    Dim error As ValidationError
                    For Each error In validator.Validate(manager, activity)
                        If Not [error].UserData.Contains(GetType(Activity)) Then
                            [error].UserData.Item(GetType(Activity)) = activity
                        End If
                        results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError([error], parameters))
                    Next
                Catch exception As TargetInvocationException
                    Dim exception2 As Exception = If(exception.InnerException <>  Nothing , exception.InnerException, exception)
                    Dim error2 As New ValidationError(SR.GetString("Error_ValidatorThrewException", New Object() { exception2.GetType.FullName, validator.GetType.FullName, activity.Name, exception2.ToString }), &H627)
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error2, parameters))
                Catch exception3 As Exception
                    Dim error3 As New ValidationError(SR.GetString("Error_ValidatorThrewException", New Object() { exception3.GetType.FullName, validator.GetType.FullName, activity.Name, exception3.ToString }), &H627)
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error3, parameters))
                End Try
            Next
        End Sub


        ' Properties
        Private Shared ReadOnly Property StandardAssemblies As StringCollection
            Get
                Dim strings As New StringCollection
                strings.Add("System.Workflow.ComponentModel.dll")
                strings.Add("System.Workflow.Runtime.dll")
                strings.Add("System.Workflow.Activities.dll")
                strings.Add("System.dll")
                strings.Add("System.Transactions.dll")
                strings.Add("System.drawing.dll")
                strings.Add("System.Web.dll")
                strings.Add("System.Web.Services.dll")
                Return strings
            End Get
        End Property


        ' Fields
        Friend Shared ColumnNumber As Object = New Object
        Friend Shared LineNumber As Object = New Object

        ' Nested Types
        Friend NotInheritable Class WorkflowCompilerOptionsService
            Implements IWorkflowCompilerOptionsService
            ' Methods
            Friend Sub New(ByVal rootNamespace As String)
                Me.rootNamespace = String.Empty
                Me.rootNamespace = rootNamespace
            End Sub

            Friend Sub New(ByVal parameters As WorkflowCompilerParameters)
                Me.rootNamespace = String.Empty
                If ((Not parameters.CompilerOptions Is Nothing) AndAlso (CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse) = SupportedLanguages.VB)) Then
                    Dim match As Match = New Regex("\s*[/-]rootnamespace[:=]\s*(?<RootNamespace>[^\s]*)").Match(parameters.CompilerOptions)
                    If match.Success Then
                        Me.rootNamespace = match.Groups.Item("RootNamespace").Value
                    End If
                End If
                Me.language = parameters.LanguageToUse
                Me.checkTypes = parameters.CheckTypes
            End Sub


            ' Properties
            Private ReadOnly Property System.Workflow.ComponentModel.Compiler.IWorkflowCompilerOptionsService.CheckTypes As Boolean
                Get
                    Return Me.checkTypes
                End Get
            End Property

            Private ReadOnly Property System.Workflow.ComponentModel.Compiler.IWorkflowCompilerOptionsService.Language As String
                Get
                    Return Me.language
                End Get
            End Property

            Private ReadOnly Property System.Workflow.ComponentModel.Compiler.IWorkflowCompilerOptionsService.RootNamespace As String
                Get
                    Return Me.rootNamespace
                End Get
            End Property


            ' Fields
            Private checkTypes As Boolean
            Private language As String
            Private rootNamespace As String
        End Class
    End Class
End Namespace

